package com.cg.springSecurity;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootApplication
@MapperScan("com.cg.springSecurity.mapper")
@ComponentScan(basePackages = {"com.cg"})
public class SpringSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }
    @Configuration
    public static class CorsConfig {
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            //  你需要跨域的地址  注意这里的 127.0.0.1 != localhost
            // * 表示对所有的地址都可以访问
            corsConfiguration.addAllowedOriginPattern("*");
            //  跨域的请求头
            corsConfiguration.addAllowedHeader("*"); // 2
            //  跨域的请求方法
            corsConfiguration.addAllowedMethod("*"); // 3
            //加上了这一句，大致意思是可以携带 cookie
            //最终的结果是可以 在跨域请求的时候获取同一个 session
            corsConfiguration.setAllowCredentials(true);
            return corsConfiguration;
        }
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            //配置 可以访问的地址
            source.registerCorsConfiguration("/**", buildConfig()); // 4
            return new CorsFilter(source);
        }
        //用于服务端发送http请求
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }
}
